<?php

$raw = file_get_contents("php://input");
$input = json_decode($raw, true);
$action = $input['action'];
$payload = $input['payload'];
log_file(var_export($payload, true));
#$tablename = 'swatmb_belbin_test';
if ($raw == '' || $raw == null) {
    log_file('backend');
    die('backend.php');
}
#entrances
if ($action == 'upload') {
    if (!isDuplicated($payload)) {
        commitData($payload);
        echo '0';
    } else {
        echo '1';
    }
} elseif ($action == 'verify') {
    $output = array('valid' => verifyAdmin($payload['token']));
    log_file(var_export($output, true));
    echo json_encode($output, JSON_UNESCAPED_UNICODE);
} elseif ($action == 'load') {
    if (verifyAdmin($payload['token'])) {
        $output = array('content' => loadContent());
        log_file(var_export($output, true));
        echo json_encode($output, JSON_UNESCAPED_UNICODE);
    }
}
die();

function loadContent()
{
    $sql = 'SELECT * FROM swatmb_belbin_test';
    $result = db_exec($sql);
    $resource = array();
    while ($row = mysqli_fetch_assoc($result)) {
        array_push($resource, $row);
    }
    log_file(json_encode($resource, JSON_UNESCAPED_UNICODE));
    return $resource;
}
function verifyAdmin($token)
{
    if ($token == '8570') {
        return true;
    }
    return false;
}

function commitData($payload)
{
    $time = date("Y-m-d H:i:s");
    $usrinfo = json_encode($payload['usrinfo'], JSON_UNESCAPED_UNICODE);
    $belbin = json_encode($payload['belbin'], JSON_UNESCAPED_UNICODE);
    $holland = json_encode($payload['holland'], JSON_UNESCAPED_UNICODE);
    $name = $payload['usrinfo']['name'];
    $id = $payload['usrinfo']['id'];
    log_file(var_export($id, true));
    $sql = "INSERT INTO swatmb_belbin_test VALUES (null,'{$time}',{$id},'{$name}','{$usrinfo}','{$belbin}','{$holland}')";
    log_file($sql);
    db_exec($sql);
}

function isDuplicated($payload)
{
    $usrid = $payload['usrinfo']['id'];
    $usrnm = $payload['usrinfo']['name'];
    $sql = "SELECT * FROM swatmb_belbin_test WHERE id = {$usrid} AND name = '{$usrnm}'";
    $result = db_exec($sql);
    if (mysqli_num_rows($result) > 0) {
        return true;
    } else {
        return false;
    }
}

function log_file($text)
{
    $content = '[' . date("Y-m-d H:i:s") . '] ' . $text;
    $file_path = './logfile.txt';
    $file = fopen($file_path, 'a');
    fwrite($file, "{$content}\r\n");
    fclose($file);
}

function db_exec($sql)
{
    $dbhost = 'localhost';
    $dbusr = 'cdapp';
    $dbpwd = 'gzzxjjwt1';
    $bdname = 'cdapp';
    $link = mysqli_connect($dbhost, $dbusr, $dbpwd, $bdname);
    if (!$link) {
        log_file(mysqli_connect_errno() . ': ' . mysqli_connect_error());
        return null;
    }
    mysqli_query($link, "set character set 'utf8'");
    mysqli_query($link, "set names 'utf8'");
    if ($result = mysqli_query($link, $sql)) {
        mysqli_close($link);
        return $result;
    }
    log_file(mysqli_error($link));
    mysqli_close($link);
    return null;
}
